package com.lw.mall.web.lw;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.lw.mall.config.AlipayTemplate;
import com.lw.mall.service2.OrderService2;
import com.lw.mall.vo.PayAsyncVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 支付宝订单支付回调 在公网上面生效
 * 120.78.234.151
 * http://120.78.234.151/mall/payed/notify
 * 返回success 后支付宝不会发送请求
 */
@Slf4j
@RestController
public class AliPayOrderController {

    @Autowired
    private OrderService2 orderService2;

    @Autowired
    private AlipayTemplate alipayTemplate;

    /**
     * 支付宝发送请求
     * @return
     */
    @PostMapping("/payed/notify")
    public String orderStatus(HttpServletRequest request, PayAsyncVo payAsyncVo) throws AlipayApiException {
//        final Map<String, String[]> parameterMap = request.getParameterMap();

        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名
        if(signVerified){
            log.info("签名验证成功...");
            String result = orderService2.handlePayResult(payAsyncVo);
            return result;
        }else {
            log.info("签名验证失败...");
            return "error";
        }
    }
}
